const express = require("express");
const router = express.Router();
const models = require("../models");
const Op = models.Sequelize.Op; // 模糊查询的时候需要用到

// 查询总结列表
router.get("/list", async function (req, res, next) {
  const where = {};
  const currentPage = parseInt(req.body.currentPage) || 1; // 分页参数
  const pageSize = parseInt(req.body.pageSize) || 10; // 分页参数
  // const name = req.body.name;
  // if (name) {
  //   where.name = {
  //     [Op.like]: "%" + name + "%",
  //   };
  // }
  const result = await models.Summary.findAndCountAll({
    order: [["id", "desc"]], // 根据某个字段进行排序， desc-降序 asc-升序
    where: where,
    offset: (currentPage - 1) * pageSize,
    limit: pageSize,
  });
  res.json({
    code: 200,
    msg: "操作成功",
    data: {
      total: result.count,
      currentPage: currentPage,
      pageSize: pageSize,
      data: result.rows,
    },
  });
});

// 新增总结
router.post("/", async function (req, res, next) {
  await models.Summary.create({
    societyId: req.body.societyId,
    content: req.body.content,
    activityId: req.body.activityId,
    imgUrlOne: req.body.imgUrlOne,
    imgUrlTwo: req.body.imgUrlTwo,
  });
  res.json({
    code: 200,
    msg: "操作成功",
  });
});

// 查询总结
router.get("/:id", async function (req, res, next) {
  const data = await models.Summary.findByPk(req.params.id);
  res.json({
    code: 200,
    msg: "操作成功",
    data: data,
  });
});

// 修改总结
router.put("/", async function (req, res, next) {
  // findByPk是通过主键查找
  const result = await models.Summary.findByPk(req.body.id);
  result.update(req.body);
  res.json({
    code: 200,
    msg: "操作成功",
  });
});

// 删除总结
router.delete("/:id", async function (req, res, next) {
  const result = await models.Summary.findByPk(req.params.id);
  result.destroy(req.body);
  res.json({
    code: 200,
    msg: "操作成功",
  });
});

// 查询指定总结
router.delete("/:id", async function (req, res, next) {
  const result = await models.Summary.findByPk(req.params.id);
  res.json({
    code: 200,
    msg: "操作成功",
    data: result,
  });
});

module.exports = router;
